package com.qiu.greened.ui.my

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.qiu.greened.databinding.ActivityRegisterBinding
import android.text.style.StrikethroughSpan
import android.text.style.UnderlineSpan
import android.text.method.LinkMovementMethod

import android.text.style.ClickableSpan
import android.view.View
import cn.smssdk.SMSSDK
import com.mob.MobSDK
import com.qiu.greened.utils.showToast
import android.os.CountDownTimer
import android.text.*
import android.util.Log
import android.widget.Toast
import androidx.core.content.edit
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import cn.smssdk.EventHandler
import cn.smssdk.wrapper.TokenVerifyResult
import com.qiu.greened.MainActivity
import com.qiu.greened.bean.UserPostBean
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.network.UserService
import com.qiu.greened.utils.MyData
import kotlinx.coroutines.launch


class RegisterActivity : AppCompatActivity() {

    private lateinit var binding: ActivityRegisterBinding
    private var codeOk = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRegisterBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //标题栏
        supportActionBar?.let {
            it.setHomeButtonEnabled(true)
            it.setDisplayHomeAsUpEnabled(true)
            it.title = "注册"
        }
        setCode() //设置验证码
        setAgreement() //设置用户协议
        setRegisterButton() //设置注册按钮


    }

    private fun setCode() {
        MobSDK.submitPolicyGrantResult(true, null)
        val eh: EventHandler = object : EventHandler() {
            override fun afterEvent(event: Int, result: Int, data: Any) {
                when (result) {
                    SMSSDK.RESULT_COMPLETE -> {
                        //成功回调
                        when (event) {
                            SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE -> {
                                //提交短信、语音验证码成功
                                val mData: HashMap<String, Object> = data as HashMap<String, Object>
                                val phone = mData["phone"] as String
                                if (phone == binding.editPhone.text.toString()) {
                                    codeOk = true
                                }
                            }
                        }
                    }
                    else -> {
                        (data as Throwable).printStackTrace()
                    }
                }
            }
        }
        SMSSDK.registerEventHandler(eh) //注册短信回调
        binding.btnCode.setOnClickListener {
            val phone: String = binding.editPhone.text.toString()
            binding.editLayoutPhone.error = when {
                phone == "" -> "手机号不能为空"
                phone.length < 11 -> "请输入正确的手机号"
                else -> null
            }
            if (binding.editLayoutPhone.error == null) {
                SMSSDK.getVerificationCode("86", phone)
                val mCountDownTimer = object : CountDownTimer(60 * 1000, 1000) {
                    override fun onTick(millisUntilFinished: Long) {
                        binding.btnCode.text = (millisUntilFinished / 1001).toString() + " 秒"
                        binding.btnCode.isClickable = false
                    }

                    override fun onFinish() {
                        binding.btnCode.text = "重新获取验证码"
                        binding.btnCode.isClickable = true
                    }
                }
                mCountDownTimer.start()
            }
        }
        binding.editCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(editable: Editable) {
                if (editable.toString().length == 6) {
                    val phone: String = binding.editPhone.text.toString()
                    SMSSDK.submitVerificationCode("86", phone, editable.toString())
                }
            }
        })
    }

    private fun setAgreement() {
        val string = SpannableStringBuilder()
        string.append("我同意《用户隐私协议》")
        val clickableSpan: ClickableSpan = object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = Color.parseColor("#FF0090FF") //设置颜色
                ds.isUnderlineText = false //去掉下划线
            }

            override fun onClick(view: View) {
                startActivity(Intent(this@RegisterActivity, AgreementActivity::class.java))
            }
        }
        string.setSpan(clickableSpan, 3, string.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        binding.checkAgreement.text = string
        binding.checkAgreement.highlightColor = Color.TRANSPARENT; //设置点击后的颜色为透明，否则会一直出现高亮
        binding.checkAgreement.movementMethod = LinkMovementMethod.getInstance();//触发点击事件

    }

    private fun setRegisterButton() {
        binding.btnRegister.setOnClickListener {
            val phone: String = binding.editPhone.text.toString()
            val password: String = binding.editPassword.text.toString()
            val code: String = binding.editCode.text.toString()
            binding.editLayoutPhone.error = when {
                phone == "" -> "手机号不能为空"
                phone.length < 11 -> "请输入正确的手机号"
                else -> null
            }
            binding.editLayoutPassword.error = when (password) {
                "" -> "密码不能为空"
                else -> null
            }
            binding.editLayoutCode.error = when {
                code == "" -> "验证码不能为空"
                code.length < 6 -> "请输入正确的验证码"
                !codeOk -> "验证码错误"
                else -> null
            }
            if (!binding.checkAgreement.isChecked) {
                "您需要同意用户隐私协议".showToast()
            }
            if (binding.editLayoutPhone.error == null && binding.editLayoutPassword.error == null && codeOk && binding.checkAgreement.isChecked) {
                register(phone, password)
            }
        }
    }

    private fun register(phone: String, password: String) {
        lifecycleScope.launch {
            try {
                val data = ServiceCreator.create<UserService>()
                    .getUserRegisterData(UserPostBean(phone, password)).dataConvert()
                getSharedPreferences("data", Context.MODE_PRIVATE).edit {
                    putString("phone", phone)
                    putString("password", password)
                    putInt("userId", data.userId)
                    putString("userName", data.userName)
                    putString("userAvatar", data.userAvatar)
                    putString("token", data.token)
                }
                MyData.setLoginData()
                "注册成功".showToast()
                startActivity(Intent(this@RegisterActivity, MainActivity::class.java))
                finish()
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(applicationContext, "${e.message}", Toast.LENGTH_SHORT).show()
                Log.i("请求失败", "${e.message}")
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish() // back button
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}